import os
import logging
import logging.config

from . import utils
LOG = logging.getLogger(__name__)


def set_logging(log_name=None):
    """"""
    base_dir = os.environ.get('OUTPUT_DIR', os.path.join(os.getcwd(), 'output'))
    log_dir = os.path.join(base_dir, 'log')
    utils.make_dirs_if_not_exist(log_dir)
    log_name = log_name or "{}.log".format(utils.get_now_day())
    log_abs_path = os.path.abspath(os.path.join(log_dir, log_name))
    logging_config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {
                'format': '%(asctime)s [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
            },
            'standard': {
                'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
            },
        },

        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "stream": "ext://sys.stdout"
            },

            "default": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "simple",
                "filename": log_abs_path,
                'mode': 'w+',
                "maxBytes": 1024 * 1024 * 5,  # 5 MB
                "backupCount": 20,
                "encoding": "utf8"
            },
        },

        # "loggers": {
        #     "app_name": {
        #         "level": "INFO",
        #         "handlers": ["console"],
        #         "propagate": "no"
        #     }
        # },

        "root": {
            'handlers': ['default', 'console'],
            'level': "INFO",
            'propagate': False
        }
    }
    logging.config.dictConfig(logging_config)
    LOG.info('set log config, log_file={}'.format(log_abs_path))
